const MarketRegionDao = require('../dao/marketRegion');
const ValidatorMarketRegion = require('../validators/marketRegion');
const ok = require('../core/response-shortcut');


class marketRegionController {

    static async cuMarketRegion(ctx) {
        // 接收客户端参数
        let req = ctx.request.body;

        //验证器,如果验证不通过,直接在验证器里报错
        await ValidatorMarketRegion.cuMarketRegion(req)

    //验证通过,就操作数据库
        //===>创建MarketRegion并写入sql
        if (req.id) {
            await MarketRegionDao.uMarketRegion(req);
        } else { 
            await MarketRegionDao.cMarketRegion(req);
        }
        ctx.response.status = 200;
        ctx.body = ok.success()
    }


    /**
     * 获取某个标签详情
     * @param marketRegionId
     * @returns {Promise.<void>}
     */
    static async rdMarketRegion(ctx) {
        /**
         * 仅限get
         * 读取或删除MarketRegion
         * 可读取单个或所有
         * api和id参数皆为空,则读取所有
         * api为空,但id有值,读取单个权限对应的中文
         * api为del,则id必填,删除单个权限
         * @param ctx
         */
        // 接收客户端参数
        let params = ctx.request.query;

        if (params.id) {
            //验证器,如果验证不通过,直接在验证器里报错
            await ValidatorMarketRegion.rdMarketRegion(params.id)
            //===>去数据库搜索id
            ctx.response.status = 200;
            if (params.api === 'del') {
                let data = await MarketRegionDao.dMarketRegion(params.id);
                //删除成功返回1,否则是0
                if (data == 1) {
                    ctx.body = ok.success('删除成功')
                } else {
                    ctx.body = ok.fail('删除失败,可能未找到对应id')
                }
            } else {
                //读取某个id对应权限的中文名
                let data = await MarketRegionDao.rMarketRegion(params.id);
                console.log('======data康康', data);
                ctx.body = ok.json(data)
            }
        } else {
            //===>取出所有MarketRegion
            var arr_allMarketRegion = await MarketRegionDao.getAllMarketRegion();
            ctx.response.status = 200;
            ctx.body = ok.json(arr_allMarketRegion)
        }
    }

}

module.exports = marketRegionController